package com.blaze.framework.core.util.domain;

import com.blaze.framework.core.util.exception.CheckedException;
import com.blaze.framework.core.util.uitls.AssertUtil;
import lombok.Builder;
import lombok.Data;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.time.LocalDateTime;
import java.util.Set;

/**
 * 获取TOKEN信息
 *
 * @author created by Zhou Zongbo on 2025/6/4.
 */
@Data
@Builder
public class TokenInfo {
    /**
     * 用户ID
     */
    private String userId;

    /**
     * 用户名称
     */
    private String username;

    /**
     * 角色集合
     */
    private Set<String> roles;

    /**
     * 授权过期时间
     */
    private LocalDateTime expireTime;


    /**
     * TOKEN有效性校验
     */
    public void valid(Set<String> gatewayFilterRoles) {
        AssertUtil.notNull(expireTime, "授权过期时间不能为空.");
        AssertUtil.isTrue(expireTime.isBefore(LocalDateTime.now()), "授权已过期，请重新登录.");
        if (CollectionUtils.isNotEmpty(gatewayFilterRoles)) {
            if (CollectionUtils.isEmpty(roles)) {
                throw new CheckedException("当前用户无权限");
            }

            boolean permission = roles.containsAll(gatewayFilterRoles);
            if (Boolean.FALSE.equals(permission)) {
                throw new CheckedException("当前用户权限不足");
            }
        }
    }

    public Long getUserId() {
        return StringUtils.isBlank(userId) ? null : Long.valueOf(userId);
    }
}
